<?php
require_once dirname(__FILE__) . '/phpmailer/class.phpmailer.php';

class Mailer
{
    private static $instance = false;
    private $phpmailer = false;
    private $error = false;
    private $isStoreLocal = false;

    private function __construct()
    {
        $config = include dirname(__FILE__) . '/config.php';

        $this->phpmailer = new phpmailer();

        $this->isStoreLocal = $config['store_local'];

        if($config['smtp'] === true)
        {
            $this->phpmailer->Mailer = 'smtp';
            $this->phpmailer->SMTPSecure = $config['smtp_secure'];
            $this->phpmailer->Host = $config['smtp_host'];
            $this->phpmailer->Port = $config['smtp_port'];

            if($config['smtp_user'] != false)
            {
                $this->phpmailer->SMTPAuth  = true;
                $this->phpmailer->Username  = $config['smtp_user'];
                $this->phpmailer->Password  = $config['smtp_pass'];
            }
        }

        $this->phpmailer->From = $this->phpmailer->Sender = $config['from_email'];
        $this->phpmailer->FromName = $config['from_name'];

        $this->phpmailer->IsHTML(true);
    }

    private function __clone()
    {
    }

    private static function getInstance()
    {
        if (self::$instance === false)
        {
            self::$instance = new Mailer();
        }

        return self::$instance;
    }

    private function send($email, $subject, $body, $priority=3)
    {
        $this->error = false;

        $this->phpmailer->Priority = $priority;

        $this->phpmailer->Subject = $subject;
        $this->phpmailer->Body = $body;
        $this->phpmailer->AddAddress($email);

        $result = $this->phpmailer->Send();

        $this->phpmailer->ClearAddresses();
        $this->phpmailer->ClearAttachments();

        if ($result == false)
        {
            $this->error = 'Can not send email';
        }

        if($this->isStoreLocal === true)
        {
            $mailDir = realpath(dirname(__FILE__) . '/../logs/');

            if (!is_dir($mailDir))
            {
                mkdir($mailDir, 0777);
            }

            $f = fopen($mailDir . '/' . date('Y_m_d__H_i', time()) . '.txt', 'w');

            if ($f)
            {
                fwrite($f, $subject . "\n\n");
                fwrite($f, $body);
                fclose($f);
            }
        }

        return $result;
    }

    public static function getError()
    {
        return self::getInstance()->error;
    }

    public static function sendMessage($email, $subject, $body, $priority = 3)
    {
        return self::getInstance()->send($email, $subject, $body, $priority);
    }
}
